package com.vancouver.knows.ui.activity.userpost;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.vancouver.knows.R;
import com.vancouver.knows.business.bean.CategoryInfo;
import com.vancouver.knows.business.bean.SubcategoryInfo;
import com.vancouver.knows.business.service.impl.FetchUserPostCategoriesHandler;
import com.vancouver.knows.business.task.mark.FetchUserPostCategoriesTaskMark;
import com.vancouver.knows.ui.base.BaseActivity;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-18.
 */
public class UserPostSubcategoryListActivity extends BaseActivity implements IResultReceiver, AdapterView.OnItemClickListener {

    public static final String CATEGORY_EXTRA = "category_extra";
    public static final String IS_CITY_CATEGORY_EXTRA = "is_city_extra";
    public static final String SELECTED_CITY_DATA = "selected_city_data";
    public static final String REQUEST_CODE_EXTRA = "request_code_extra";

    public static final int CHOOSE_CITY_REQUEST = 567;
    public static final int CHOOSE_NEW_SUBCATEGORY_REQUEST = 568;

    @Bind(R.id.subcategory_title)
    TextView mTitle;
    @Bind(R.id.subcategories_listview)
    ListView mSubcategoriesListView;
    @Bind(R.id.loading_view)
    RelativeLayout mLoadingView;

    private String mChosenCategory;
    private SubcategoryListViewAdapter mSubcategoriesAdapter;

    private boolean mIsCityList = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subcategory_list);

        if (getIntent() == null) {
            return;
        }

        mIsCityList = getIntent().getBooleanExtra(IS_CITY_CATEGORY_EXTRA, false);

        if (!mIsCityList) {
            mChosenCategory = getIntent().getStringExtra(CATEGORY_EXTRA);
            if (StringUtil.isEmptyString(mChosenCategory)) {
                return;
            }

            switch (mChosenCategory) {

                case UserPostFilterActivity.BUY_AND_SELL_SLUG:
                    mTitle.setText(R.string.category_buy_and_sell);
                    break;

                case UserPostFilterActivity.FRIENDS_AND_PARTNERS_SLUG:
                    mTitle.setText(R.string.category_friends_and_partners);
                    break;

                case UserPostFilterActivity.HOUSING_SLUG:
                    mTitle.setText(R.string.category_housing);
                    break;

                case UserPostFilterActivity.JOBS_SLUG:
                    mTitle.setText(R.string.category_jobs);
                    break;

                case UserPostFilterActivity.MUTUAL_SUPPORT_SLUG:
                    mTitle.setText(R.string.category_mutual_support);
                    break;

            }
        } else {
            mTitle.setText(R.string.area_title);
        }

        HashMap categoryMap = imContext.getBusinessModule().getCacheManager().getUserPostCategories();
        if (!categoryMap.isEmpty()) {
            setSubcategoryData(categoryMap);
        } else {
            imContext.getBusinessModule().getServiceWrapper().fetchUserPostCategories(this, new FetchUserPostCategoriesTaskMark());
        }
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {

        if (mIsCityList) {
            if (mSubcategoriesAdapter.getSelectedCity() != null) {
                Intent data = new Intent();
                data.putExtra(SELECTED_CITY_DATA, mSubcategoriesAdapter.getSelectedCity());
                setResult(RESULT_OK, data);
            }
        }

        super.onBackPressed();
    }

    private void setSubcategoryData(HashMap categoryMap) {

        mLoadingView.setVisibility(View.GONE);

        if (!mIsCityList) {
            List<CategoryInfo> categoryInfoList = (List<CategoryInfo>) categoryMap.get(FetchUserPostCategoriesHandler.USERPOST_CATEGORIES);
            List<SubcategoryInfo> subcategories = null;

            for (CategoryInfo categoryInfo : categoryInfoList) {
                if (categoryInfo.getSlug().equals(mChosenCategory)) {
                    subcategories = categoryInfo.getSubcategories();
                    break;
                }
            }

            if (subcategories != null) {
                mSubcategoriesAdapter = new SubcategoryListViewAdapter(this, subcategories.subList(1, subcategories.size())); // do not show the "All" subcategory in the list.
                mSubcategoriesListView.setAdapter(mSubcategoriesAdapter);
                mSubcategoriesListView.setOnItemClickListener(this);
            }
        } else {
            List<String> cityList = (List<String>) categoryMap.get(FetchUserPostCategoriesHandler.CITY_LIST);
            String selectedCity = getIntent().getStringExtra(SELECTED_CITY_DATA);
            if (cityList != null) {
                mSubcategoriesAdapter = new SubcategoryListViewAdapter(this, cityList.subList(1, cityList.size()), true);
                if (!StringUtil.isEmptyString(selectedCity)) {
                    mSubcategoriesAdapter.setSelectedCity(selectedCity);
                }
                mSubcategoriesListView.setAdapter(mSubcategoriesAdapter);
                mSubcategoriesListView.setOnItemClickListener(this);
            }
        }
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {

        if (exception != null) {
            Log.e(TAG, exception.getExMessage());
        }

        HashMap categoryMap = imContext.getBusinessModule().getCacheManager().getUserPostCategories();
        if (categoryMap != null) {
            setSubcategoryData(categoryMap);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (!mIsCityList) {
            if (getIntent().getIntExtra(REQUEST_CODE_EXTRA, 0) != CHOOSE_NEW_SUBCATEGORY_REQUEST) {
                Intent intent = new Intent(this, CreateUserPostActivity.class);
                intent.putExtra(CATEGORY_EXTRA, mChosenCategory);
                SubcategoryInfo subcategoryInfo = (SubcategoryInfo) mSubcategoriesAdapter.getItem(position);
                intent.putExtra(CreateUserPostActivity.SUBCATEGORY_EXTRA, subcategoryInfo);
                intent.putExtra(CreateUserPostActivity.SUBCATEGORY_PRICE_EXTRA, subcategoryInfo.getPrice());
                startActivityForResult(intent, CreateUserPostActivity.CREATE_POST_SUCCESS_REQUEST);
            } else {
                Intent intent = new Intent();
                intent.putExtra(CATEGORY_EXTRA, mChosenCategory);
                SubcategoryInfo subcategoryInfo = (SubcategoryInfo) mSubcategoriesAdapter.getItem(position);
                intent.putExtra(CreateUserPostActivity.SUBCATEGORY_EXTRA, subcategoryInfo);
                intent.putExtra(CreateUserPostActivity.SUBCATEGORY_PRICE_EXTRA, subcategoryInfo.getPrice());
                setResult(RESULT_OK, intent);
                finish();
            }
        } else {
            mSubcategoriesAdapter.setSelectedCity(position);
            onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CreateUserPostActivity.CREATE_POST_SUCCESS_REQUEST && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    public static class SubcategoryListViewAdapter extends BaseAdapter {

        private LayoutInflater mLayoutInflater;
        private List<SubcategoryInfo> mSubcategories;
        private List<String> mCities;

        private boolean mIsCityList = false;
        private int mChosenItem = -1;
        private String mSelectedCityString = "";

        public SubcategoryListViewAdapter(Context context, List<SubcategoryInfo> subcategories) {
            this.mLayoutInflater = LayoutInflater.from(context);
            this.mSubcategories = subcategories;
        }

        public SubcategoryListViewAdapter(Context context, List<String> cities, boolean isCityList) {
            this.mLayoutInflater = LayoutInflater.from(context);
            this.mCities = cities;
            this.mIsCityList = isCityList;
        }

        @Override
        public int getCount() {
            if (!mIsCityList) {
                return mSubcategories.size();
            } else {
                return mCities.size();
            }
        }

        @Override
        public Object getItem(int position) {
            if (!mIsCityList) {
                return mSubcategories.get(position);
            } else {
                return mCities.get(position);
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                if (!mIsCityList) {
                    convertView = mLayoutInflater.inflate(R.layout.result_view_item, parent, false);
                } else {
                    convertView = mLayoutInflater.inflate(R.layout.view_radio_item, parent, false);
                }

                viewHolder = new ViewHolder(convertView);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            if (!mIsCityList) {
                SubcategoryInfo subcategoryInfo = (SubcategoryInfo) getItem(position);
                viewHolder.title.setText(subcategoryInfo.getName());
                viewHolder.icon.setVisibility(View.GONE);
            } else {
                String city = (String) getItem(position);
                viewHolder.title.setText(city);

                if (position == mChosenItem || city.equals(mSelectedCityString)) {
                    viewHolder.icon.setImageResource(R.drawable.checkmark);
                    viewHolder.icon.setBackgroundResource(R.drawable.checkmark_selected);
                } else {
                    viewHolder.icon.setImageResource(0);
                    viewHolder.icon.setBackgroundResource(R.drawable.checkmark_unselected);
                }
            }

            return convertView;
        }

        public String getSelectedCity() {
            if (mIsCityList) {
                if (mChosenItem != -1) {
                    return mCities.get(mChosenItem);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

        public void setSelectedCity(int position) {
            this.mChosenItem = position;
            this.mSelectedCityString = "";
            notifyDataSetChanged();
        }

        public void setSelectedCity(String selectedCity) {
            mSelectedCityString = selectedCity;
        }

        public static class ViewHolder {

            @Bind(R.id.icon)
            ImageView icon;
            @Bind(R.id.title)
            TextView title;

            public ViewHolder (View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
